package com.moodbox.server.user.controller;

import cn.hutool.core.bean.BeanUtil;
import com.moodbox.server.common.annotation.RequireRole;
import com.moodbox.server.common.enums.UserRoleEnum;
import com.moodbox.server.user.dto.UserProfileDTO;
import com.moodbox.server.user.dto.WxLoginDTO;
import com.moodbox.server.user.entity.User;
import com.moodbox.server.user.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
@Validated
public class UserController {

    private final UserService userService;

    /**
     * 微信登录
     * @param wxLoginDTO 微信登录信息
     * @return 用户信息和Token
     */
    @PostMapping("/wx-login")
    public ResponseEntity<Map<String, Object>> wxLogin(
        @Valid @RequestBody WxLoginDTO wxLoginDTO
    ) {
        // 执行微信登录
        User user = userService.wxLogin(wxLoginDTO);

        // 生成用户Token
        String token = userService.generateUserToken(user);

        // 构建响应
        Map<String, Object> response = new HashMap<>();
        response.put("user", user);
        response.put("token", token);

        log.info("用户{}微信登录成功", user.getId());
        return ResponseEntity.ok(response);
    }

    /**
     * 更新用户信息
     * @param user 用户信息
     * @return 更新后的用户信息
     */
    @PostMapping("/update")
    public ResponseEntity<User> updateUser(
        @RequestBody User user, 
        HttpServletRequest request
    ) {
        // 确保只能更新当前登录用户的信息
        String userId = (String) request.getAttribute("userId");
        user.setId(userId);
        User updatedUser = userService.updateUser(user);
        return ResponseEntity.ok(updatedUser);
    }

    /**
     * 更新用户角色（仅管理员可操作）
     * @param userId 用户ID
     * @param role 新角色
     * @return 更新后的用户信息
     */
    @PostMapping("/update-role")
    @RequireRole(value = UserRoleEnum.ADMIN)
    public ResponseEntity<User> updateUserRole(
        @RequestParam String userId, 
        @RequestParam UserRoleEnum role,
        HttpServletRequest request
    ) {
        String adminId = (String) request.getAttribute("userId");
        User updatedUser = userService.updateUserRole(userId, role);
        log.info("管理员{}更新用户{}角色为{}", adminId, userId, role);
        return ResponseEntity.ok(updatedUser);
    }

    /**
     * 获取用户信息
     * @param userId 用户ID
     * @return 用户信息
     */
    @GetMapping("/info")
    public ResponseEntity<User> getUserInfo(
        HttpServletRequest request
    ) {
        String userId = (String) request.getAttribute("userId");
        User user = userService.getUserById(userId);
        return ResponseEntity.ok(user);
    }

    /**
     * 验证用户Token
     * @param token 用户Token
     * @return 用户ID
     */
    @PostMapping("/validate-token")
    public ResponseEntity<Map<String, String>> validateToken(
        @RequestParam String token
    ) {
        String userId = userService.validateUserToken(token);
        Map<String, String> response = new HashMap<>();
        response.put("userId", userId);
        return ResponseEntity.ok(response);
    }

    /**
     * 完善用户信息
     * @param profileDTO 用户信息
     * @return 更新后的用户信息
     */
    @PostMapping("/complete-profile")
    public ResponseEntity<Map<String, Object>> completeProfile(
        @Valid @RequestBody UserProfileDTO profileDTO,
        HttpServletRequest request
    ) {
        String userId = (String) request.getAttribute("userId");
        
        // 完善用户信息
        User updatedUser = userService.completeProfile(userId, profileDTO);

        // 生成新的Token
        String token = userService.generateUserToken(updatedUser);

        // 构建响应
        Map<String, Object> response = new HashMap<>();
        response.put("user", updatedUser);
        response.put("token", token);
        response.put("profileComplete", true);

        log.info("用户{}完善个人信息", userId);
        return ResponseEntity.ok(response);
    }

    /**
     * 检查用户信息是否完整
     * @return 是否完整
     */
    @GetMapping("/profile-status")
    public ResponseEntity<Map<String, Object>> checkProfileStatus(
        HttpServletRequest request
    ) {
        String userId = (String) request.getAttribute("userId");
        boolean isComplete = userService.isProfileComplete(userId);

        Map<String, Object> response = new HashMap<>();
        response.put("profileComplete", isComplete);

        return ResponseEntity.ok(response);
    }

    /**
     * 获取用户详细信息
     * @return 用户详细信息
     */
    @GetMapping("/details")
    public ResponseEntity<User> getUserDetails(
        HttpServletRequest request
    ) {
        String userId = (String) request.getAttribute("userId");
        User user = userService.getUserDetails(userId);
        return ResponseEntity.ok(user);
    }
    
    /**
     * 获取用户统计信息
     * @return 用户统计信息
     */
    @GetMapping("/stats")
    public ResponseEntity<Map<String, Object>> getUserStats(
        HttpServletRequest request
    ) {
        String userId = (String) request.getAttribute("userId");
        
        // 构建统计信息响应
        Map<String, Object> stats = new HashMap<>();
        stats.put("totalRecords", 10); // 示例数据，实际应从数据库查询
        stats.put("continuousDays", 5);
        stats.put("averageMoodScore", 3.8);
        
        log.info("获取用户{}统计信息", userId);
        return ResponseEntity.ok(stats);
    }
} 